<?php

class CssHelper extends Helper
{

  protected $content = array();

  protected $minifyAll = true;

  /**
   *
   * @param string $file Absolute or relative path to css file, with or without extension
   * @param boolean $minify
   * @param boolean $inline
   * @return void
   */
  public function load($file, $minify = true, $inline = true)
  {
    if (! sy_url_is_absolute($file)) {
      $file = sy_fix_path(s::config()->get('theme_dir') . '/css/' . $file);
    }

    $file = sy_fix_extension($file, 'css');

    $this->minifyAll = $this->minifyAll && $minify;
    $this->content[] = array('minify' => $minify, 'inline' => $inline, 'file' => $file, 'content' => file_get_contents($file));
  }

  public function dump($minify = true)
  {
    $output = '';

    $output .= '<style>';

    $css = '';
    foreach ($this->content as $row) {
      if ($minify && $row['minify'] && ! $this->minifyAll) {
        $css .= $this->minify($row['content']);
      }
      else {
        $css .= $row['content'];
      }
    }

    if ($minify && $this->minifyAll) {
      $css = $this->minify($css);
    }

    $output .= $css . '</style>';

    return $this->output($output);
  }

  protected function minify($css)
  {
    if (is_dir(SY_DIR . '/lib/minify')) {
      /*$cache = new FileCache();

      $id = md5(serialize($css));

      if ($cache->cached($id)) {
        $css = $cache->read($id);
      }
      else {
        set_include_path(SY_DIR . '/lib/minify/lib/' . PATH_SEPARATOR . get_include_path());
        require_once ('Minify/CSS.php');
        $css = Minify_CSS::minify($css);
     		$cache->write($id, $css);
      }*/

      set_include_path(SY_DIR . '/lib/minify/lib/' . PATH_SEPARATOR . get_include_path());
      require_once ('Minify/CSS.php');
      $css = Minify_CSS::minify($css);
    }

    return $css;
  }

  public function start()
  {
    ob_start();
  }

  public function end($minify = true, $inline = true)
  {
    $content = ob_get_clean();
    $content = preg_replace('#</?style( .*?)?>#i', '', $content);
    $this->content[] = array('minify' => $minify, 'inline' => $inline, 'content' => $content);
  }

}

?>